package com.ihr360.payroll.service.batch.impl;

import com.ihr360.commons.lang.UUIDGenerator;
import com.ihr360.job.core.repository.JobRepository;
import com.ihr360.job.endpoint.PoolStatus;
import com.ihr360.payroll.dao.BatchExecuatorStatusRepository;
import com.ihr360.payroll.model.dto.batch.BatchExecuatorStatus;
import com.ihr360.payroll.service.batch.BatchExecuatorStatusService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.List;

@Service
public class BatchExecuatorStatusServiceImpl implements BatchExecuatorStatusService {
    private final Logger logger = LoggerFactory.getLogger(BatchExecuatorStatusService.class);
    private final static String UUID = UUIDGenerator.randomUUID();
    @Autowired
    private BatchExecuatorStatusRepository batchExecuatorStatusRepository;

    @Autowired
    private JobRepository jobRepository;

    @Value("${ihr360.payroll.abandon.execution.job.minutes:30}")
    private int minutes;

    @Override
    public void updateStatus(PoolStatus poolStatus) {
        BatchExecuatorStatus status = new BatchExecuatorStatus();
        status.setId(UUID);
        status.setActiveCount(poolStatus.getActiveCount());
        status.setCorePoolSize(poolStatus.getCorePoolSize());
        status.setKeepAliveSeconds(poolStatus.getKeepAliveSeconds());
        status.setMaxPoolSize(poolStatus.getMaxPoolSize());
        status.setUpdateDate(Calendar.getInstance().getTime());
        batchExecuatorStatusRepository.save(status);
    }


    public Iterable<BatchExecuatorStatus> poolStatus() {
        return batchExecuatorStatusRepository.findAll();
    }

    @Override
    @Transactional
    public int clearOutdateExecuator() {
        return batchExecuatorStatusRepository.clearOutdateExecuator();
    }

    @Override
    public int abandonLongTimeExecution() {
        int count = jobRepository.abandonLongTimeJobExecution(minutes);
        if (logger.isInfoEnabled()) {
            logger.info("++++AabandonLongTime Executions count=" + count);
        }
        return count;
    }
}